<template>
	<view class="content pc-tou-gao " >
		<!-- 用于头像裁剪的Canvas -->
		<canvas canvas-id="cropCanvas" style="width: 200px; height: 200px; position: absolute; left: -9999px;"></canvas>
		<view class="scroll-fix" >

		
			<view class="d-kuan-juzhong ">
				<!--头部-->
				<view class="d-kuan pc-dingbu ">
					<DToubu 
					@login-success="handleLoginSuccess" 
					@logout-success="handleLogout"
					:dengluxianshi="denglu_xianshi"
					@update-dengluxianshi="handleUpdateDengluxianshi"
					></DToubu>
					
				</view>

				<!--头部-->
				<!--下面内容-->
				<view class="d-kuan d-clear">
					<uv-row customStyle="margin-bottom: 10px" :gutter="10">
						<!-- #ifdef H5 -->
						<uv-col span="2" class="pc-yincang">
							<!--左边导航-->
							<view class="d-daohang d-you-10 pc-yincang d-y-gundong d-shang-20" id="zuo-daohang" :style="{height: leftNavHeight}">
								<view class="d-daohang-5 " >
									<Ddaohang 
									@denglu-fabu="denglu_fabu"
									
									></Ddaohang>
								</view>
							</view>
						</uv-col>
						<!-- #endif -->

						<uv-col :span="kuan_shu">

							
							<view class="d-shang-50">
								<view class="d-waikuang-20-0 d-beijing-bai ">
									<!--头部-->
									<Dfanhui
									:title="'头像设置'"
									>

									</Dfanhui>
									<view class="d-kuan">
										<uv-cell title="头像设置" :titleStyle="{ fontSize: '38rpx' }" @click="url('touxiang')">
											<template v-slot:value>

												<uv-image :src="u_data.wo && u_data.wo.avatar" width="40px" height="40px" shape="circle"></uv-image>
											</template>
											<!-- 自定义右侧图标 -->
										</uv-cell>
									</view>															
										<view class="d-kuan">
											<!--头像截图-->

											<!-- 上传图片预览和裁剪区域 -->
											<view v-if="imagePath" class="avatar-crop-container" style="user-select: none; -webkit-user-select: none; -moz-user-select: none; -ms-user-select: none;">
												<view class="crop-preview-wrapper" style="user-select: none; -webkit-user-select: none; -moz-user-select: none; -ms-user-select: none;">
													<image :src="imagePath" mode="widthFix" class="preview-image" 
					:style="{ 
						transform: `translate(${imagePositionX}px, ${imagePositionY}px) scale(${imageScale})`,
						transformOrigin: 'center',
						transition: 'none',
						width: imageWidth + 'px',
						height: '300px',
						display: 'block',
						userSelect: 'none',
						pointerEvents: isDragging ? 'none' : 'auto'
					}" 
					@load="onImageLoad"
					@touchstart="onImageTouchStart"
					@touchmove="onImageTouchMove"
					@touchend="onImageTouchEnd"
					@mousedown="onImageMouseDown"
					@mousemove="onImageMouseMove"
					@mouseup="onImageMouseUp"
					@mouseleave="onImageMouseUp"
					@wheel="onImageWheel"></image>
					<!-- 裁剪框 -->
					<view class="crop-box" :style="{width: cropSize + 'px', height: cropSize + 'px', left: cropX + 'px', top: cropY + 'px'}" 
						@touchstart="onCropBoxTouchStart" @touchmove="onCropBoxTouchMove" @touchend="onCropBoxTouchEnd"
						@mousedown="onCropBoxMouseDown" @mousemove="onCropBoxMouseMove" @mouseup="onCropBoxMouseUp" @mouseleave="onCropBoxMouseUp">
						<view class="crop-grid"></view>
						<!-- 调整大小的句柄 -->
						<div class="resize-handle resize-handle-nw" @mousedown="onResizeStart($event, 'nw')"></div>
						<div class="resize-handle resize-handle-ne" @mousedown="onResizeStart($event, 'ne')"></div>
						<div class="resize-handle resize-handle-sw" @mousedown="onResizeStart($event, 'sw')"></div>
						<div class="resize-handle resize-handle-se" @mousedown="onResizeStart($event, 'se')"></div>
					</view>
				</view>

				<view class="crop-actions">
							<!--view class="crop-slider">
								<text>调整裁剪框大小</text>
								<slider min="100" max="300" v-model="cropSize" show-value></slider>
							</view>
							<view class="crop-slider">
								<text>缩放图片</text>
								<slider min="0.5" max="2" v-model="imageScale" step="0.1" show-value></slider>
							</view-->
							<view class="crop-buttons">
								<uv-button size="small" text="重新选择" @click="d_shangchuan"></uv-button>
								<uv-button type="primary" size="small" text="确认裁剪" @click="handleCrop"></uv-button>
							</view>
					</view>
				</view>

				</view>			
						<view class="d-neikuang-40">
							<uv-row customStyle="margin-bottom: 10px" gutter="10">
								<uv-col span="6">
									<uv-button class="d-shang-20 d-clear" text="上传头像" @click="d_shangchuan"></uv-button>
								</uv-col>
								<uv-col span="6">
									<uv-button class="d-shang-20 d-clear"  color="linear-gradient(to right, rgb(66, 83, 216), rgb(213, 51, 186))" text="确认修改" @click="d_xiugai" :disabled="!croppedImagePath"></uv-button>
								</uv-col>
							</uv-row>
							<!-- 裁剪后的图片预览 -->
							<view v-if="croppedImagePath" class="cropped-preview">
								<text class="preview-title">裁剪结果预览</text>
								<image :src="croppedImagePath" mode="aspectFit" class="cropped-image"></image>
							</view>

							
						</view>
					</view>
				
				</view>
							
							
							
															
							
							<view class="pc-neikuang-20-list" >
								
							</view>
							
							<!--头部背景-->
							
							
						</uv-col>
						<!-- #ifdef H5 -->
						<uv-col span="3" class="pc-yincang">
							<view class="d-daohang d-you-10 pc-yincang d-shang-20" id="zuo-daohang" :style="{height: leftNavHeight}">
								<view class="d-you-kuang">
									
								</view>
							</view>
						</uv-col>
						<!-- #endif -->
					</uv-row>

					

				</view>
				<!--下面内容-->


			</view>

			<view class="d-clear"></view>
		
		</view>
		
		

	</view>
</template>

<script>
    import Api from '@/utils/api.js'; 
	import QuanApi from '@/utils/quan_api.js';
	import UApi from '@/utils/u_api.js';
	import { getRequest,postRequest } from '@/utils/wxRequest.js';
    //引入组件 d-toubu
    import DToubu from '@/components/d-toubu/d-toubu.vue'
	import Ddaohang from '@/components/d-daohang/d-daohang.vue'
	import Dweibu from '@/components/d-weibu/d-weibu.vue'
	import Dfanhui from '@/components/d-fanhui/d-fanhui.vue'
	//import Dtouxiang from '@/components/lxiaoxiao-cropperi/lxiaoxiao-cropper.vue'
	
	
	
	export default {
		data() {
			return {
				
				title: 'Hello',
				leftNavHeight: '300rpx', // 默认高度
                rightColWidth: '300px', // 默认宽度
				rightColLeft: '0px', // 添加这个属性
				uiddata:{},
				erjidata:[],
				erjiindex:'',//当前激活的二级菜单索引
				activeIndex: -1, // 当前激活的一级菜单索引
				zhishi_tuijian_data:[], // 知识推荐数据
				zhishi_daohang_list:[], // 知识导航列表
				zhishi_list:[], // 知识列表
				haibao_data:[], // 海报数据
				imageSize: {
        		    width: 0,
        		    height: 0
        		},
				tubiaolist: 
				['integral', 'kefuv-ermai', 'coupon', 'gift', 'scan',
					'pause-circle', 'volume-off', 'email', 'list'
				],
				denglu_xianshi:0, // 登录显示

				tiezi_list:[], // 帖子列表

				currentPage: 1, //下拉加载
    			pageSize: 12, //下拉加载
    			isLoading: false, //下拉加载
    			noMoreData: false, //下拉加载
				
				kuan_shu: 7, //格大小
				uid: '', // 用户ID - 初始化为空字符串，将在onLoad/onShow中设置
				swiperHeight: '250',
				gao: '20', //图片高度
				
				quan_data:[],
				
				shenhe_shu:0,//审核帖子数量
				u_data:[], // 用户信息
				dataLoaded: false,
			
				guanzhu_panduan:0,
				
				// 头像截图相关状态
					imagePath: '', // 上传的图片路径
					croppedImagePath: '', // 裁剪后的图片路径
					cropSize: 120, // 裁剪框大小设置为260rpx
					cropX: 20, // 裁剪框X坐标
					cropY: 20, // 裁剪框Y坐标
					imageHeight: 300, // 预览图片高度
					imageWidth: 300, // 预览图片宽度
					isDragging: false, // 是否正在拖动裁剪框
					touchOffsetX: 0, // 触摸点相对于裁剪框的X偏移
					touchOffsetY: 0, // 触摸点相对于裁剪框的Y偏移
					imageScale: 1, // 图片缩放比例，默认为1
					initialImageWidth: 0, // 原始图片宽度
					initialImageHeight: 0, // 原始图片高度
					initialDistance: null, // 双指触摸的初始距离，用于缩放计算
					imagePositionX: 0, // 图片水平偏移位置
					imagePositionY: 0, // 图片垂直偏移位置
					isImageDragging: false, // 图片是否正在拖动
					touchStartX: 0, // 触摸开始时的X坐标
					touchStartY: 0, // 触摸开始时的Y坐标
					imageStartX: 0, // 触摸开始时的图片X位置
					imageStartY: 0, // 触摸开始时的图片Y位置
					// 裁剪框调整大小相关状态
					isResizing: false, // 是否正在调整裁剪框大小
					resizeDirection: null, // 调整大小的方向 (nw, ne, sw, se)
					resizeStartX: 0, // 调整大小开始时的X坐标
					resizeStartY: 0, // 调整大小开始时的Y坐标
					resizeStartSize: 0 // 调整大小开始时的裁剪框大小

			}
		},
		components: {
  		    DToubu,
			Ddaohang,
			Dweibu,
			Dfanhui,
			//Dtouxiang,
  		},
		mounted() {
			// 确保在组件挂载后更新uid
			// console.log('Component mounted, checking uid...');
			const storeUid = this.$store.state.memberuid;
			if (storeUid && !this.uid) {
				this.uid = storeUid;
				// console.log('UID set from store in mounted:', this.uid);
			}
			
    	    
			this.getRightColWidth(); // 添加这行
    	    // 添加窗口大小变化监听
			// #ifdef H5
			this.setLeftNavHeight();
    	    window.addEventListener('resize', this.setLeftNavHeight);
			window.addEventListener('resize', this.getRightColWidth); // 添加窗口大小变化监听
			// #endif
			var e = this;
			//this.onImageLoad(e);
    	},
    	beforeDestroy() {
    	    // 移除监听
			// #ifdef H5
    	    window.removeEventListener('resize', this.setLeftNavHeight);
			window.removeEventListener('resize', this.getRightColWidth); // 添加这行
			// #endif
    	},
		onShow() {
			// console.log('Component shown, updating uid...');
			const storeUid = this.$store.state.memberuid;
			// console.log('Store memberuid:', storeUid);
			this.uid = storeUid;
			// console.log('UID set in onShow:', this.uid);

			if(!storeUid){
				// console.log('No uid in store, showing login prompt');
				this.denglu_xianshi = 1;
				this.godenglu(); // 暂时注释掉自动跳转，便于调试
			}

			//this.getShenhe_shu_api();
			
		},
		onLoad(e) {
			// console.log('Component loaded with params:', e);
			// 优先使用路由参数中的uid
			if (e && e.uid) {
				this.uid = e.uid;
				// console.log('UID set from route params:', this.uid);
			} else {
				// 如果路由参数中没有uid，则从store获取
				const storeUid = this.$store.state.memberuid;
				if (storeUid) {
					this.uid = storeUid;
					// console.log('UID set from store in onLoad:', this.uid);
				} else {
					// console.log('No uid available in route params or store');
				}
			}
			
			// 只有在有uid的情况下才调用API
			if (this.uid) {
				this.getu_api();
				// 初始化昵称数据
				this.setInitialNicheng();
			
			} else {
				console.warn('Cannot call getu_api: uid is not available');
			}
			
		},
		computed: {
		  yidenglu() {
		    return (this.$store.state.memberuid && this.$store.state.keycode) ? 1 : 0;
		  },
		  touxiang() {
		    return this.$store.state.member? this.$store.state.member.avatar : '';
		  },
		  name1() {
		    return this.$store.state.member? this.$store.state.member.name : '';
		  },
		  pc() {
		    return this.$store.state.kuan.pc;
		  },
		},
		// 由于这是头像设置页面，不需要下拉加载功能
		// onReachBottom() {
		//   // 如需下拉加载，请实现正确的加载逻辑
		// },

		methods: {
			// 图片加载处理 - 获取预览区域实际宽度并限制在300px以内
	onImageLoad(e) {
			// 使用SelectorQuery获取预览区域的实际宽度
			const query = uni.createSelectorQuery().in(this);
			query.select('.crop-preview-wrapper').boundingClientRect(data => {
				if (data) {
					// 限制实际预览区域宽度不超过300px
					this.imageWidth = Math.min(300, data.width);
					// console.log('获取到实际预览宽度：', this.imageWidth);
					// 重新计算裁剪框位置，确保在图片居中的情况下也能正确居中
					const containerCenterOffset = (data.width - this.imageWidth) / 2;
					this.cropX = (this.imageWidth - this.cropSize) / 2 + containerCenterOffset;
					this.cropY = (this.imageHeight - this.cropSize) / 2;
				}
			}).exec();
    	},
		
		// 头像上传相关方法
		// 1. 上传图片
		d_shangchuan() {
			uni.chooseImage({
				count: 1,
				sizeType: ['compressed'],
				sourceType: ['album', 'camera'],
				success: (res) => {
					const tempFilePath = res.tempFilePaths[0];
					this.imagePath = tempFilePath;
					this.croppedImagePath = ''; // 清除之前的裁剪结果
					this.imageScale = 1; // 重置缩放比例
					this.imagePositionX = 0; // 重置图片位置
					this.imagePositionY = 0;
					
					// 获取图片信息并设置预览高度和宽度，限制在300px之内
					uni.getImageInfo({
						src: tempFilePath, // 修正参数名为src
						success: (imageInfo) => {
							// 保存原始图片尺寸
							this.initialImageWidth = imageInfo.width;
							this.initialImageHeight = imageInfo.height;
							
							// 限制图片宽度和高度都不超过300px
							if (imageInfo.width > imageInfo.height) {
								// 宽度大于高度，按宽度限制
								this.imageWidth = Math.min(300, imageInfo.width);
								const ratio = this.imageWidth / imageInfo.width;
								this.imageHeight = Math.round(imageInfo.height * ratio);
							} else {
								// 高度大于等于宽度，按高度限制
								this.imageHeight = Math.min(300, imageInfo.height);
								const ratio = this.imageHeight / imageInfo.height;
								this.imageWidth = Math.round(imageInfo.width * ratio);
							}
							// 初始化裁剪框位置，确保在图片居中的情况下也能正确居中
							this.$nextTick(() => {
								// 使用SelectorQuery获取预览区域的实际宽度
								const query = uni.createSelectorQuery().in(this);
								query.select('.crop-preview-wrapper').boundingClientRect(data => {
									if (data) {
										// 计算预览容器宽度与图片宽度的差值，使裁剪框在预览容器中居中
										const containerCenterOffset = (data.width - this.imageWidth) / 2;
										this.cropX = (this.imageWidth - this.cropSize) / 2 + containerCenterOffset;
										this.cropY = (this.imageHeight - this.cropSize) / 2;
									}
								}).exec();
							});
						},
						fail: (err) => {
							// console.log('获取图片信息失败', err);
						}
					});
				},
				fail: (err) => {
					// console.log('选择图片失败', err);
				}
			});
		},
		
		// 2. 处理裁剪框拖动开始
			onCropBoxTouchStart(e) {
				this.isDragging = true;
				// 记录相对于裁剪框的触摸位置
				const query = uni.createSelectorQuery().in(this);
				query.select('.crop-preview-wrapper').boundingClientRect(data => {
					if (data) {
						// 计算相对于预览区域的触摸位置
						const relativeX = e.touches[0].clientX - data.left;
						const relativeY = e.touches[0].clientY - data.top;
						
						// 记录相对于裁剪框的触摸位置
						this.touchOffsetX = relativeX - this.cropX;
						this.touchOffsetY = relativeY - this.cropY;
						// 保存预览区域的位置信息，避免在move事件中重复查询
						this.previewWrapperRect = data;
					}
				}).exec();
			},
			
			// 3. 处理裁剪框拖动
			onCropBoxTouchMove(e) {
				if (!this.isDragging || !this.previewWrapperRect) return;
				
				// 阻止默认行为，防止页面滚动
				e.preventDefault();
				
				// 计算相对于预览区域的触摸位置
				const relativeX = e.touches[0].clientX - this.previewWrapperRect.left;
				const relativeY = e.touches[0].clientY - this.previewWrapperRect.top;
				
				// 计算新的裁剪框位置（相对位置减去偏移量）
				let newX = relativeX - this.touchOffsetX;
				let newY = relativeY - this.touchOffsetY;
				
				// 使用实际的图片预览宽度作为限制
				const previewWidth = this.previewWrapperRect.width;
				newX = Math.max(0, Math.min(previewWidth - this.cropSize, newX));
				newY = Math.max(0, Math.min(this.imageHeight - this.cropSize, newY));
				
				this.cropX = newX;
				this.cropY = newY;
			},
			
			// 4. 处理裁剪框拖动结束
			onCropBoxTouchEnd() {
				this.isDragging = false;
				// 清除保存的预览区域信息
				this.previewWrapperRect = null;
			},
			
			// 鼠标事件处理 - 兼容PC浏览器
			onCropBoxMouseDown(e) {
				this.isDragging = true;
				// 阻止默认行为防止文字选中和页面滚动
				e.preventDefault();
				e.stopPropagation();
				// 记录相对于裁剪框的触摸位置
				const query = uni.createSelectorQuery().in(this);
				query.select('.crop-preview-wrapper').boundingClientRect(data => {
					if (data) {
						// 计算相对于预览区域的触摸位置
						const relativeX = e.clientX - data.left;
						const relativeY = e.clientY - data.top;
						
						// 记录相对于裁剪框的触摸位置
						this.touchOffsetX = relativeX - this.cropX;
						this.touchOffsetY = relativeY - this.cropY;
						// 保存预览区域的位置信息，避免在move事件中重复查询
						this.previewWrapperRect = data;
					}
				}).exec();
			},
			
			onCropBoxMouseMove(e) {
				if (!this.isDragging || !this.previewWrapperRect) return;
				// 阻止默认行为防止文字选中和页面滚动
				e.preventDefault();
				e.stopPropagation();
				 
				// 计算相对于预览区域的触摸位置
				const relativeX = e.clientX - this.previewWrapperRect.left;
				const relativeY = e.clientY - this.previewWrapperRect.top;
				 
				// 计算新的裁剪框位置（相对位置减去偏移量）
				let newX = relativeX - this.touchOffsetX;
				let newY = relativeY - this.touchOffsetY;
				 
				// 使用实际的图片预览宽度作为限制
				const previewWidth = this.previewWrapperRect.width;
				newX = Math.max(0, Math.min(previewWidth - this.cropSize, newX));
				newY = Math.max(0, Math.min(this.imageHeight - this.cropSize, newY));
				 
				// 节流优化：只有当位置变化超过1像素时才更新
				if (Math.abs(newX - this.cropX) > 0.5 || Math.abs(newY - this.cropY) > 0.5) {
					this.cropX = newX;
					this.cropY = newY;
					// 使用requestAnimationFrame优化渲染
					requestAnimationFrame(() => {
						this.$forceUpdate();
					});
				}
			},
			
			onCropBoxMouseUp() {
				this.isDragging = false;
				// 清除保存的预览区域信息
				this.previewWrapperRect = null;
			},
		
		// 开始调整裁剪框大小
					onResizeStart(e, direction) {
						e.preventDefault();
						this.isResizing = true;
						this.resizeDirection = direction;
						this.resizeStartX = e.clientX;
						this.resizeStartY = e.clientY;
						this.resizeStartSize = this.cropSize;
						this.resizeStartXCoord = this.cropX;
						this.resizeStartYCoord = this.cropY;
						
						// 监听鼠标移动和释放事件
						// #ifdef H5
						document.addEventListener('mousemove', this.onResizeMove);
						document.addEventListener('mouseup', this.onResizeEnd);
						document.addEventListener('mouseleave', this.onResizeEnd);
						// #endif
					},
					
					// 调整裁剪框大小的移动事件
					onResizeMove(e) {
						if (!this.isResizing) return;
						e.preventDefault();
						
						// 获取移动距离
						const deltaX = e.clientX - this.resizeStartX;
						const deltaY = e.clientY - this.resizeStartY;
						
						// 限制最小和最大尺寸
						const minSize = 50;
						const maxSize = Math.min(this.imageWidth, this.imageHeight) * 0.8;
						
						// 根据方向调整裁剪框大小和位置
						switch (this.resizeDirection) {
							case 'se':
								// 右下角：只调整大小
								this.cropSize = Math.max(minSize, Math.min(maxSize, this.resizeStartSize + Math.max(deltaX, deltaY)));
								break;
							case 'ne':
								// 右上角：调整大小和Y位置
								const newSizeNE = Math.max(minSize, Math.min(maxSize, this.resizeStartSize + Math.max(deltaX, -deltaY)));
								const sizeDiffNE = newSizeNE - this.resizeStartSize;
								this.cropSize = newSizeNE;
								this.cropY = Math.max(0, this.resizeStartYCoord - sizeDiffNE);
								break;
							case 'sw':
								// 左下角：调整大小和X位置
								const newSizeSW = Math.max(minSize, Math.min(maxSize, this.resizeStartSize + Math.max(-deltaX, deltaY)));
								const sizeDiffSW = newSizeSW - this.resizeStartSize;
								this.cropSize = newSizeSW;
								this.cropX = Math.max(0, this.resizeStartXCoord - sizeDiffSW);
								break;
							case 'nw':
								// 左上角：调整大小、X和Y位置
								const newSizeNW = Math.max(minSize, Math.min(maxSize, this.resizeStartSize + Math.max(-deltaX, -deltaY)));
								const sizeDiffNW = newSizeNW - this.resizeStartSize;
								this.cropSize = newSizeNW;
								this.cropX = Math.max(0, this.resizeStartXCoord - sizeDiffNW);
								this.cropY = Math.max(0, this.resizeStartYCoord - sizeDiffNW);
								break;
						}
						
						// 确保裁剪框不会超出预览区域
						const maxX = this.imageWidth - this.cropSize;
						const maxY = this.imageHeight - this.cropSize;
						this.cropX = Math.max(0, Math.min(maxX, this.cropX));
						this.cropY = Math.max(0, Math.min(maxY, this.cropY));
						
						// 强制更新视图
						this.$forceUpdate();
					},
					
					// 结束调整裁剪框大小
					onResizeEnd() {
						this.isResizing = false;
						this.resizeDirection = null;
						
						// 移除事件监听
						// #ifdef H5
						document.removeEventListener('mousemove', this.onResizeMove);
						document.removeEventListener('mouseup', this.onResizeEnd);
						document.removeEventListener('mouseleave', this.onResizeEnd);
						// #endif
					},
					
					// 5. 确认裁剪
					handleCrop() {
						// 使用uni-app的canvas进行裁剪
						const ctx = uni.createCanvasContext('cropCanvas');
						
						// 检查imagePath是否存在
						if (!this.imagePath) {
							uni.showToast({
								title: '请先选择图片',
								icon: 'none'
							});
							return;
						}
			
			// 获取原始图片信息
					uni.getImageInfo({
						src: this.imagePath, // 修正参数名为src
						success: (imageInfo) => {
							// console.log('获取图片信息成功:', imageInfo);
							// 计算裁剪比例 - 使用原始图片的实际尺寸计算比例
							const previewRatio = imageInfo.width / this.imageWidth;
							const cropWidth = this.cropSize * previewRatio;
							const cropHeight = this.cropSize * previewRatio;
							
							// 获取预览容器的实际尺寸
							const query = uni.createSelectorQuery().in(this);
							query.select('.crop-preview-wrapper').boundingClientRect(data => {
								if (data) {
									// 考虑图片缩放和偏移后的裁剪位置
									// 由于使用了 transformOrigin: 'center'，需要调整计算方式
									const scaledImageWidth = this.imageWidth * this.imageScale;
									const scaledImageHeight = this.imageHeight * this.imageScale;
									 
									// 计算图片在预览区域中的实际位置（考虑transform: center和translate）
									const actualImageX = (data.width - scaledImageWidth) / 2 + this.imagePositionX;
									const actualImageY = (data.height - scaledImageHeight) / 2 + this.imagePositionY;
									 
									// 计算裁剪框相对于图片的位置
									const relativeCropX = this.cropX - actualImageX;
									const relativeCropY = this.cropY - actualImageY;
									 
									// 转换为原始图片的裁剪位置
									// 注意：由于使用了transformOrigin: 'center'，图片缩放时中心保持不变
									// 所以需要先计算相对于缩放后图片中心的偏移，再应用缩放逆变换
									const scaledImageCenterX = scaledImageWidth / 2;
									const scaledImageCenterY = scaledImageHeight / 2;
									const relativeCenterX = relativeCropX - scaledImageCenterX;
									const relativeCenterY = relativeCropY - scaledImageCenterY;
									 
									// 先除以缩放比例得到相对于原始图片中心的偏移，再加上原始图片中心位置
									const originalImageCenterX = this.imageWidth / 2;
									const originalImageCenterY = this.imageHeight / 2;
									const originalRelativeX = (relativeCenterX / this.imageScale) + originalImageCenterX;
									const originalRelativeY = (relativeCenterY / this.imageScale) + originalImageCenterY;
									 
									// 最后乘以预览比例得到原始图片上的实际裁剪位置
									const cropX = originalRelativeX * previewRatio;
									const cropY = originalRelativeY * previewRatio;
									
									// 确保裁剪坐标为非负值
									const finalCropX = Math.max(0, cropX);
									const finalCropY = Math.max(0, cropY);
									 
									// console.log('裁剪参数 - previewRatio:', previewRatio, 'cropX:', cropX, 'cropY:', cropY, 'cropSize:', this.cropSize, 'imageScale:', this.imageScale);
									
									// 清除canvas之前的内容
									ctx.clearRect(0, 0, 200, 200);
									
									// 正确的裁剪方式：从原图中截取裁剪区域并绘制到canvas上
									// 使用修正后的裁剪坐标
									const sourceX = Math.max(0, Math.min(imageInfo.width - cropWidth, finalCropX));
									const sourceY = Math.max(0, Math.min(imageInfo.height - cropHeight, finalCropY));
									ctx.drawImage(this.imagePath, sourceX, sourceY, cropWidth, cropHeight, 0, 0, 200, 200);
									ctx.draw(false, () => {
										// 将canvas内容导出为图片
										uni.canvasToTempFilePath({
											canvasId: 'cropCanvas',
											// 设置导出区域为裁剪框大小
											x: 0,
											y: 0,
											width: 200, // 使用canvas实际大小作为导出宽度
											height: 200, // 使用canvas实际大小作为导出高度
											quality: 0.9,
											success: (res) => {
												// console.log('导出图片成功:', res.tempFilePath);
												this.croppedImagePath = res.tempFilePath;
												// 将裁剪后的图片路径临时设置到预览头像位置，实现即时预览效果
												if (!this.u_data) {
													this.u_data = {};
												}
												if (!this.u_data.wo) {
													this.u_data.wo = {};
												}
												this.u_data.wo.avatar = res.tempFilePath;
												uni.showToast({
													title: '裁剪成功',
													icon: 'success'
												});
											},
											fail: (err) => {
												// console.log('导出图片失败', err);
												uni.showToast({
													title: '裁剪失败，请重试',
													icon: 'none'
												});
											}
										}, this); // 注意这里需要传入this作为第二个参数
									});
								}
							}).exec();
						},
						fail: (err) => {
							// console.log('获取图片信息失败', err);
							uni.showToast({
								title: '获取图片信息失败',
								icon: 'none'
							});
						}
					});
		},
		
		// 6. 图片触摸开始（用于缩放和拖动）
				onImageTouchStart(e) {
					if (e.touches.length === 2) {
						// 记录两个触摸点之间的距离作为初始距离
						const dx = e.touches[0].clientX - e.touches[1].clientX;
						const dy = e.touches[0].clientY - e.touches[1].clientY;
						this.initialDistance = Math.sqrt(dx * dx + dy * dy);
					} else if (e.touches.length === 1) {
						// 单指触摸时处理拖动
						this.isImageDragging = true;
						this.touchStartX = e.touches[0].clientX;
						this.touchStartY = e.touches[0].clientY;
						this.imageStartX = this.imagePositionX;
						this.imageStartY = this.imagePositionY;
					}
				},
				
				// 7. 图片触摸移动（用于缩放和拖动）
				onImageTouchMove(e) {
					// 如果是双指触摸，处理缩放
					if (e.touches.length === 2) {
						// 阻止默认行为，防止页面滚动
						e.preventDefault();
						e.stopPropagation();
									 
						// 计算当前两个触摸点之间的距离
						const dx = e.touches[0].clientX - e.touches[1].clientX;
						const dy = e.touches[0].clientY - e.touches[1].clientY;
						const currentDistance = Math.sqrt(dx * dx + dy * dy);
									 
						// 只有当初始距离存在时才进行计算
						if (this.initialDistance) {
							// 计算缩放比例变化
							const scaleFactor = currentDistance / this.initialDistance;
							// 更新缩放比例，但限制在最小0.5和最大2之间
							const oldScale = this.imageScale;
							let newScale = Math.max(0.5, Math.min(2, this.imageScale * scaleFactor));
							// 更新初始距离为当前距离，以便下一帧继续计算
							this.initialDistance = currentDistance;
									 
							// 节流优化：只有当缩放比例变化超过0.01时才更新
							if (Math.abs(newScale - this.imageScale) > 0.01) {
								this.imageScale = newScale;
								// 使用requestAnimationFrame优化渲染
								requestAnimationFrame(() => {
									this.$forceUpdate();
								});
							}
						}
					} 
					// 如果是单指触摸且正在拖动图片
					else if (e.touches.length === 1 && this.isImageDragging) {
						// 阻止默认行为，防止页面滚动
						e.preventDefault();
						e.stopPropagation();
									 
						// 计算移动距离
						const deltaX = e.touches[0].clientX - this.touchStartX;
						const deltaY = e.touches[0].clientY - this.touchStartY;
									 
						// 更新图片位置
						let newX = this.imageStartX + deltaX;
						let newY = this.imageStartY + deltaY;
									 
						// 节流优化：只有当位置变化超过1像素时才更新
						if (Math.abs(newX - this.imagePositionX) > 0.5 || Math.abs(newY - this.imagePositionY) > 0.5) {
							this.imagePositionX = newX;
							this.imagePositionY = newY;
							// 使用requestAnimationFrame优化渲染
							requestAnimationFrame(() => {
								this.$forceUpdate();
							});
						}
					}
				},
				
				// 8. 图片触摸结束
				onImageTouchEnd() {
					// 清除初始距离
					this.initialDistance = null;
					// 清除图片拖动状态
					this.isImageDragging = false;
				},
				
				// 9. 图片鼠标按下（用于PC浏览器拖动）
				onImageMouseDown(e) {
					// 只有在左键点击时才处理拖动
					if (e.button === 0) {
						this.isImageDragging = true;
						this.touchStartX = e.clientX;
						this.touchStartY = e.clientY;
						this.imageStartX = this.imagePositionX;
						this.imageStartY = this.imagePositionY;
						// 阻止默认行为，防止图片被拖动到别处
						e.preventDefault();
					}
				},
				
				// 10. 图片鼠标移动（用于PC浏览器拖动）
				onImageMouseMove(e) {
					if (this.isImageDragging) {
						// 阻止默认行为，防止页面滚动和文字选中
						e.preventDefault();
						e.stopPropagation();
							 
						// 计算移动距离
						const deltaX = e.clientX - this.touchStartX;
						const deltaY = e.clientY - this.touchStartY;
							 
						// 更新图片位置
						let newX = this.imageStartX + deltaX;
						let newY = this.imageStartY + deltaY;
							 
						// 节流优化：只有当位置变化超过1像素时才更新
						if (Math.abs(newX - this.imagePositionX) > 0.5 || Math.abs(newY - this.imagePositionY) > 0.5) {
							this.imagePositionX = newX;
							this.imagePositionY = newY;
							// 使用requestAnimationFrame优化渲染
							requestAnimationFrame(() => {
								this.$forceUpdate();
							});
						}
					}
				},
				
				// 11. 图片鼠标松开（用于PC浏览器拖动）
				onImageMouseUp() {
					this.isImageDragging = false;
				},
				
				// 12. 图片鼠标滚轮（用于PC浏览器缩放）
			onImageWheel(e) {
				// 阻止默认行为
				e.preventDefault();
				
				// 调试信息：显示deltaY的值
				// console.log('wheel event:', e.deltaY);
				// console.log('current scale:', this.imageScale);
				
				// 更稳健的滚轮方向检测，同时考虑可能的反向值
				const isScrollingDown = e.deltaY > 0 || (e.deltaY === 0 && e.wheelDelta < 0);
				
				if (!isScrollingDown) {
					// 向上滚动 - 放大
					/*this.imageScale = Math.min(2, this.imageScale + 0.1);
					// console.log('放大后:', this.imageScale);*/
				} else {
					// 向下滚动 - 缩小
					/*this.imageScale = Math.max(0.5, this.imageScale - 0.1);
					// console.log('缩小后:', this.imageScale);*/
				}
				
				// 强制Vue更新DOM，确保缩放立即生效
				this.$forceUpdate();
			},
				
		// 9. 确认修改（上传到服务器）
		d_xiugai() {
			var uid = this.$store.state.memberuid;
			var keycode = this.$store.state.keycode;
			if (!this.croppedImagePath) {
				uni.showToast({
					title: '请先上传并裁剪头像',
					icon: 'none'
				});
				return;
			}
			
			// 显示加载提示
			uni.showLoading({
				title: '上传中...'
			});
			
			// 直接使用uni.uploadFile上传文件，这是更通用的方法
			uni.uploadFile({
				url: Api.postTouxiang(uid, keycode),
				filePath: this.croppedImagePath,
				name: 'file',
				formData: {
					is_ajax: 1,
					submit: '提交'
				},
				success: (res) => {
					// 隐藏加载提示
					uni.hideLoading();
					
					// 检查响应数据
					// console.log('上传响应:', res.data);
					uni.showToast({
						title: "上传成功",
						icon: 'success',
					});
					//更新用户信息
					this.getu_api();
				},
				fail: (err) => {
					// 隐藏加载提示
					uni.hideLoading();
					
					uni.showToast({
						title: "上传失败",
						icon: 'none',
					});
					console.error('头像上传失败:', err);
				}
			});
		},
			getRightColWidth() {
				// 获取系统信息
				//const systemInfo = uni.getSystemInfoSync();
        	    // 计算可用高度（可根据实际需求调整计算方式）
        	    //const windowWidth = systemInfo.windowWidth;
				var d = this;

                this.$nextTick(() => {
				if(this.pc){
					d.gao = 20;
					d.kuan_shu = 7;
					d.swiperHeight = '250';
				} else {
					d.gao = 10;
					d.kuan_shu = 12;
					d.swiperHeight = '120';

				}
				// console.log('窗口高度:', windowWidth);

                 const query = uni.createSelectorQuery().in(this);
                 query.select('#youbiankuan').boundingClientRect(rect => {
                   if (rect) {
                     /*this.rightColWidth = `${rect.width+20}px`;
                     // console.log('右侧列宽度:', this.rightColWidth);*/
					 	this.rightColWidth = `${rect.width-80}px`;
                    	this.rightColLeft = `${rect.left}px`; // 计算左侧位置
                    	// console.log('右侧列位置:', this.rightColWidth);
                   }
                 }).exec();
               });
            },

			
			
			setLeftNavHeight() {
        	    // 获取系统信息
        	    const systemInfo = uni.getSystemInfoSync();
        	    // 计算可用高度（可根据实际需求调整计算方式）
        	    const windowHeight = systemInfo.windowHeight;
        	    const headerHeight = 70; // 头部高度估计值
        	    const calculatedHeight = windowHeight - headerHeight;
				
        	    // 设置左边导航高度
        	    this.leftNavHeight = `${calculatedHeight}px`;
        	},
			
			
			handleLoginSuccess() {
  			  this.$forceUpdate();
  			},
			
			
			
			
			denglu_fabu(){
				if(this.yidenglu == 0){
					this.denglu_xianshi = 1;
					
				} else {
					this.denglu_xianshi = 0;
						
				}
				
				// console.log('发布登录',this.denglu_xianshi);
				
			},
			// 更新判断是否登录
			handleUpdateDengluxianshi(value) {
			  this.denglu_xianshi = value;
			  
			  // console.log('关闭登录',this.denglu_xianshi);
			},
			// 退出登录
			handleLogout() {
 			  
 			  this.godenglu(); // 暂时注释掉自动跳转，便于调试
			   
 			},
			
			
			
			
			
			//个人信息
			getu_api(){
				// console.log('Calling getu_api with uid:', this.uid);
				var uid = this.$store.state.memberuid;
				var keycode = this.$store.state.keycode;
				const data = {
						uid: this.uid,
						api_auth_uid: this.uid,
						api_auth_code: keycode,
					}
				var get_data = getRequest(UApi.getU(),data);
				var res;
				get_data.then(duixin_data => {
					res = duixin_data;
					if(res.data.code) {
						if(this.uid){
							//this.u_data = res.data.data.wo;
						} else {
							//this.u_data = res.data.data.u;
						}
						this.u_data = res.data.data;
						//this.u_data = res.data.data;
						this.dataLoaded = true;
						
					}
				})

			},
			//跳转个人信息
			godenglu(){
				//保持url到缓存，名称是u_url
				uni.setStorageSync('go_url', this.$route.fullPath);
				uni.navigateTo({
					url: '/pages/u/denglu',
				})
			},

			tuichu(){
				uni.showToast({
					title: "退出成功",
					icon: 'success',
					
				})

				uni.removeStorageSync('userInfo');
				uni.removeStorageSync('memberuid');
				uni.removeStorageSync('keycode');
				uni.removeStorageSync('member');
				// 通过 mutations 更新 Vuex 状态
				this.$store.commit('setMember', {});
    			this.$store.commit('setMemberUid', '');
    			this.$store.commit('setKeycode', '');
				//this.yidenglu = 0;
				// 触发退出事件
				this.$emit('logout-success');
				//退出跳转到首页
				uni.reLaunch({ url: "/pages/index/index" });
			},
			// 设置初始昵称
			setInitialNicheng() {
				if(this.u_data && this.u_data.wo && this.u_data.wo.name && !this.uiddata.nicheng){
					this.uiddata.nicheng = this.u_data.wo.name;
				}
			},
			// 昵称设置
			d_shezhi() {
				var duixin = this;
				var nicheng = duixin.uiddata && duixin.uiddata.nicheng;
				var uid = this.$store.state.memberuid;
				var keycode = this.$store.state.keycode;
				var datas = "&is_ajax=1&data[name]="+nicheng;
				var postRenzhengRequest = postRequest(Api.postZiliao(uid,keycode),datas);
					postRenzhengRequest.then(response => {
						if (response.data.code == 1) {
							
							uni.showToast({
								title: response.data.msg,
								icon: 'success',
								success: function () {
								}
							});
							this.getu_api();
						} else {
							uni.showToast({
								title: response.data.msg,
								icon: 'error',
							});
						}
					});
			}
		}
	}
</script>

<style>
/*引入css main.css*/

	/* 头像上传和裁剪相关样式 */
	.avatar-crop-container {
		/*margin-top: 20px;*/
	}
	
	.crop-preview-wrapper {
		position: relative;
		width: 100%;
		height: 600rpx; /* 设置图片预览器最高高度为800rpx */
		background-color: #f0f0f0;
		display: flex;
		justify-content: center;
		align-items: center;
		margin-bottom: 0px;
		overflow: hidden;
	}
	
	.preview-image {
		display: block;
	}
	
	.crop-box {
			position: absolute;
			border: 2px dashed #007aff;
			background-color: rgba(0, 122, 255, 0.1);
			cursor: move;
		}
		
		/* 调整大小的句柄样式 */
		.resize-handle {
			position: absolute;
			width: 12px;
			height: 12px;
			background-color: white;
			border: 1px solid #007aff;
			box-sizing: border-box;
			z-index: 10;
		}
		
		.resize-handle-nw {
			top: -6px;
			left: -6px;
			cursor: nw-resize;
		}
		
		.resize-handle-ne {
			top: -6px;
			right: -6px;
			cursor: ne-resize;
		}
		
		.resize-handle-sw {
			bottom: -6px;
			left: -6px;
			cursor: sw-resize;
		}
		
		.resize-handle-se {
			bottom: -6px;
			right: -6px;
			cursor: se-resize;
		}
	
	.crop-grid {
		width: 100%;
		height: 100%;
		display: grid;
		grid-template-columns: repeat(3, 1fr);
		grid-template-rows: repeat(3, 1fr);
		border: 1px solid rgba(0, 122, 255, 0.3);
	}
	
	.crop-actions {
		padding: 10px;
	}
	
	.crop-slider {
		margin-bottom: 15px;
	}
	
	.crop-slider text {
		display: block;
		margin-bottom: 8px;
		font-size: 14px;
	}
	
	.crop-buttons {
		display: flex;
		justify-content: space-between;
	}
	
	.cropped-preview {
		margin-top: 20px;
		text-align: center;
	}
	
	.preview-title {
		display: block;
		margin-bottom: 10px;
		font-size: 14px;
		color: #666;
	}
	
	.cropped-image {
		width: 100px;
		height: 100px;
		/*border-radius: 50%;*/
	}
	
	/* 隐藏canvas，仅用于处理裁剪 */
	#cropCanvas {
		width: 200px;
		height: 200px;
		position: absolute;
		top: -9999px;
		left: -9999px;
	}
	
	/* 原有样式 */
	.content {
		
		
		display: flex;
		flex-direction: column;
		/*align-items: center;*/
		
		background-color: #f3f3f3;
		
		margin-bottom: 0px;
		
		/*height: 100vh;*//* 添加全屏 */
		/*width: 100vw;*/ /* 添加全屏*/
		box-sizing: border-box;
		overflow-x: hidden;

		

	}

	.logo {
		height: 200rpx;
		width: 200rpx;
		margin-top: 200rpx;
		margin-left: auto;
		margin-right: auto;
		margin-bottom: 50rpx;
	}

	.text-area {
		display: flex;
		justify-content: center;
	}

	.title {
		font-size: 36rpx;
		color: #8f8f94;
	}
	/* 屏幕宽度大于786px时隐藏uni-page-head */
    @media (min-width: 786px) {
        uni-page-head {
            display: none !important;
            opacity: 0 !important;
            height: 0 !important;
            visibility: hidden !important;
        }
    }
	/*.d-daohang{
		
		width: 600rpx;
	}*/
	/* 添加在style部分 */
	.d-daohang-zuo {
    position: fixed;
    left: 0;
    
    width: 180rpx;
    height: calc(100vh - 70rpx);
    background: #f5f5f5;
    z-index: 100;
	box-shadow: 2px 0 5px rgba(177, 177, 177, 0.1);
  }
  
  .d-daohang-you {
    position: fixed;
    left: 180rpx;
    
    width: 180rpx;
    height: calc(100vh - 70rpx);
    background: #fff;
    z-index: 100;
    box-shadow: 2px 0 5px rgba(0,0,0,0.1);
  }
   
   
   
   
   
   
   
   
 
   
  .d-erji-item {
    height: 60rpx;
    line-height: 60rpx;
    padding: 0 20rpx;
   /* border-bottom: 1px solid #f0f0f0;*/
  }
  
  .d-erji-item:active {
    background: #f5f5f5;
  }
  .you-guding {
	position: fixed;
	top: 0; /* 根据头部高度调整 */
	/*box-shadow: -2px 0 5px rgba(0,0,0,0.1);*/
	transition: all 0.3s ease;
}
/* 大于786px时的样式 */
@media screen and (min-width: 1024px) {
	.d-bianhua-10 {
		padding: 30px;
	}
	.pc-zuo-520 {
		margin-left: 520rpx;
	}
	.you-guding {
		position: fixed;
			
		top: 60px; /* 根据头部高度调整 */
		/*box-shadow: -2px 0 5px rgba(0,0,0,0.1);*/
		transition: all 0.3s ease;
	}
		
	
}
	
</style>
